package problem23;

//23.合并k个升序链表
//https://leetcode.cn/problems/merge-k-sorted-lists/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0) return null;
        return mergeSort(lists, 0, lists.length-1);
    }
    public ListNode mergeSort(ListNode[] lists, int left, int right) {
        if(left == right) return lists[left];
        int mid = left + (right - left)/2;
        ListNode head1 = mergeSort(lists, left, mid);
        ListNode head2 = mergeSort(lists, mid+1, right);

        //合并两个有序链表
        ListNode head = new ListNode();
        ListNode cur = head;
        while(head1 != null && head2 != null) {
            if(head1.val < head2.val) {
                cur.next = head1;
                head1 = head1.next;
            }else {
                cur.next = head2;
                head2 = head2.next;
            }
            cur = cur.next;
        }
        if(head1 != null) cur.next = head1;
        if(head2 != null) cur.next = head2;
        return head.next;
    }
}